package com.yunnuo.system.shiro.service;

import com.yunnuo.common.config.CommonConstant;
import com.yunnuo.common.config.UserConstants;
import com.yunnuo.common.utils.MessageUtils;
import com.yunnuo.common.utils.SystemLogUtils;
import com.yunnuo.system.domain.User;
import com.yunnuo.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
 * 登陆校验方法
 * Created by 魏洪福(15064000912@163.com) on  2018/5/25.
 */
@Component
public class LoginService
{
    @Autowired
    private PasswordService passwordService;

    @Autowired
    private IUserService userService;

    /**
     * 登录
     */
    public User login(String username, String password) throws Exception {
        User user =null;

        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            SystemLogUtils.log(username, CommonConstant.LOGIN_FAIL, MessageUtils.message("not.null"));
            throw new Exception("用户名或密码为空");
        }
        // 查询用户信息
          user = userService.selectUserByLoginName(username);

         //根据手机号码查询user（使用手机号码登陆）
        if (user == null && maybeMobilephone(username))
        {
            user = userService.selectUserByphone(username);
        }
        //根据邮箱查询user (使用邮箱登录)
        if (user == null && maybeEmail(username))
        {
            user = userService.selectUserByEmail(username);
        }

      if (user == null || user.getUserStatus().equals("1"))
        {
            SystemLogUtils.log(username, CommonConstant.LOGIN_FAIL, MessageUtils.message("user.not.exists"));
            throw new Exception("用户名或密码错误");
        }
        SystemLogUtils.log(username, CommonConstant.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        passwordService.validate(user, password);
        return user;
    }

  private boolean maybeEmail(String username)
    {
        if (!username.matches(UserConstants.EMAIL_PATTERN))
        {
            return false;
        }
        return true;
    }

    private boolean maybeMobilephone(String username)
    {
        if (!username.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN))
        {
            return false;
        }
        return true;
    }

    /**
     * 记录登陆日志
     * @param user
     */
    public void recordLoginInfo(User user)
    {

    }

}
